// ------------------------------------------------------------------------------
// 
// Copyright (c) 2007-2008 Swampware, Inc.
// 
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// 
// ------------------------------------------------------------------------------
using System;

namespace Water.Functions
{
	/// <summary>
	/// Summary description for LambdaCommand.
	/// </summary>
	public class LambdaCommand : Water.Commands.Command
	{

		public LambdaCommand()
		{
		}

		public override string Name
		{
			get { return "lambda"; }
		}

		public override object Evaluate(Water.List expressions, Water.Environment environment, Water.Evaluator evaluator)
		{
			if(expressions.Count < 2)
			{
				throw new Water.Commands.InvalidArgumentsException(this.Name, expressions);
			}


			if(!(expressions[0] is Water.List))
			{
				throw new Water.Commands.InvalidArgumentsException(this.Name, expressions);
			}
			Water.List args = ((Water.List)expressions[0]);

			Water.List parameters = new Water.List();
			for(int i = 0; i < args.Count; i++)
			{
				if(args[i] is Water.Identifier)
				{
					Water.Identifier identifier = (Water.Identifier)args[i];
					parameters.Add(identifier);
				}
				else if((args[i] is Water.Quote))
				{
					Water.Quote quote = (Water.Quote)args[i];
					Water.Identifier identifier = (Water.Identifier)quote.Expression;
					parameters.Add(new Water.Identifier("'" + identifier.Value));
				}
				else
				{
					throw new System.Exception("'" + args[i] + "' is not a valid parameter name.");
				}
			}


			return new Water.Functions.Function("lambda", parameters, expressions.NotFirst());
		}

	}
}
